package com.sui.bigdata.flink.sql.function.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class DBAes {

    public static final String UNION_IV = "(*kdiSD568?&*^KJ";
    // 加密公钥
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String KEY = "iwkdi4842@#Il$#&^&U@#$<>>??::}|HIILisliKKJilsi[lakd()^%#~*k";
//    private static Logger log = LoggerFactory.getLogger(DBAes.class);

    private DBAes() {
    }

    public static String decrypt(String cipherText) {
        return decrypt(cipherText, KEY, UNION_IV);
    }

    public static String decrypt(String cipherText, String iv) {
        String ivFinal = iv.length() > 16 ? iv.substring(0, 16) : iv;
        return decrypt(cipherText, KEY, ivFinal);
    }

    /**
     * 解密 以String密文输入,String明文输出
     *
     * @return
     */
    public static String decrypt(String cipherText, String password, String iv) {
        try {
            byte[] bytes = decrypt(Base64.decode(cipherText), password, iv);
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            //    log.error("Unsupported Encoding.");
            return cipherText;
        } catch (Exception e) {
            //   log.warn("Decrypt fail! Non-AES encrypted text: {}", cipherText);
            return cipherText;
        }
    }

    /**
     * 解密以byte[]密文输入,以byte[]明文输出
     *
     * @param byteD
     * @return
     */
    public static byte[] decrypt(byte[] byteD, String pwd, String iv) throws Exception {
        Cipher cipher;
        byte[] byteFina = null;

        cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(getKey(pwd), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        byteFina = cipher.doFinal(byteD);

        return byteFina;
    }

    /**
     * 获取随机向量,取前16位
     *
     * @return
     */
    public static String getRandomIv() {
        return UUID.randomUUID().toString().substring(0, 16);
    }

    private static byte[] getKey(String password) throws UnsupportedEncodingException {
        String key = password;
        // 使用256位密码
        if (password.length() > 16) {
            key = password.substring(0, 16);
        } else if (password.length() < 16) {
            int count = 16 - password.length();
            for (int i = 0; i < count; i++) {
                key += "0";
            }
        }
        return key.getBytes("UTF-8");
    }

    /**
     * 加密
     *
     * @param plainText 明文
     * @return
     */
    public static String encrypt(String plainText) {
        try {
            return Base64.encode(encrypt(plainText.getBytes("UTF-8"), KEY, UNION_IV));
        } catch (UnsupportedEncodingException e) {
            //log.error("Unsupported Encoding.", e);
            return null;
        }
    }

    /**
     * 加密
     *
     * @param plainText 明文
     * @param iv        16位的随机码
     * @return
     */
    public static String encrypt(String plainText, String password, String iv) {
        try {
            return Base64.encode(encrypt(plainText.getBytes("UTF-8"), password, iv));
        } catch (UnsupportedEncodingException e) {
            // log.error("Unsupported Encoding.", e);
            return null;
        }
    }

    /**
     * 加密
     *
     * @param plainText 明文
     * @param iv        16位的随机码
     * @return
     */
    public static String encrypt(String plainText, String iv) {
        try {
            String ivFinal = iv.length() > 16 ? iv.substring(0, 16) : iv;
            return Base64.encode(encrypt(plainText.getBytes("UTF-8"), KEY, ivFinal));
        } catch (UnsupportedEncodingException e) {
            // log.error("Unsupported Encoding.", e);
            return null;
        }
    }

    /**
     * 加密以byte[]明文输入,byte[]密文输出
     *
     * @param byteS
     * @return
     */
    public static byte[] encrypt(byte[] byteS, String pwd, String iv) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(getKey(pwd), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
            //log.error("encrypt error.", e);
        }
        return byteFina;
    }

    /**
     * 解密 以String名文输入,String密文输出
     *
     * @return
     */
    public static String encryptAll(String plainText, String pwd, String iv) {
        try {
            String ivFinal = iv.length() > 16 ? iv.substring(0, 16) : iv;
            return Base64.encode(encrypt(plainText.getBytes("UTF-8"), pwd, ivFinal));
        } catch (UnsupportedEncodingException e) {
            // log.error("Unsupported Encoding.", e);
            return null;
        }
    }

    public static void main(String[] args) {
//        String plainText = "abc";
//        String encryptText = encrypt(plainText);
        System.out.println(encrypt(""));
//        log.debug("encrypt: {}", encryptText);
//        System.out.println(decrypt("OiWEfijmRXVNAPMBaUZxew=="));
    }

    public static class Base64 {

        private static char Base64Code[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
                'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
                'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', '+', '/'};
        private static byte Base64Decode[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                62, -1, 63, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
                -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
                14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
                -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
                42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};

        private Base64() {
        }

        public static String encode(String code) {
            return encode(code.getBytes());
        }

        public static String encode(byte b[]) {
            int code = 0;
            StringBuffer sb = new StringBuffer((b.length - 1) / 3 << 6);
            for (int i = 0; i < b.length; i++) {
                code |= b[i] << 16 - (i % 3) * 8 & 255 << 16 - (i % 3) * 8;
                if (i % 3 == 2 || i == b.length - 1) {
                    sb.append(Base64Code[(code & 0xfc0000) >>> 18]);
                    sb.append(Base64Code[(code & 0x3f000) >>> 12]);
                    sb.append(Base64Code[(code & 0xfc0) >>> 6]);
                    sb.append(Base64Code[code & 0x3f]);
                    code = 0;
                }
            }

            if (b.length % 3 > 0)
                sb.setCharAt(sb.length() - 1, '=');
            if (b.length % 3 == 1)
                sb.setCharAt(sb.length() - 2, '=');
            return sb.toString();
        }

        public static byte[] decode(String code) {
            if (code == null)
                return null;
            int len = code.length();
            if (len % 4 != 0)
                throw new IllegalArgumentException(
                        "Base64 string length must be 4*n");
            if (code.length() == 0)
                return new byte[0];
            int pad = 0;
            if (code.charAt(len - 1) == '=')
                pad++;
            if (code.charAt(len - 2) == '=')
                pad++;
            int retLen = (len / 4) * 3 - pad;
            byte ret[] = new byte[retLen];
            for (int i = 0; i < len; i += 4) {
                int j = (i / 4) * 3;
                char ch1 = code.charAt(i);
                char ch2 = code.charAt(i + 1);
                char ch3 = code.charAt(i + 2);
                char ch4 = code.charAt(i + 3);
                int tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12
                        | Base64Decode[ch3] << 6 | Base64Decode[ch4];
                ret[j] = (byte) ((tmp & 0xff0000) >> 16);
                if (i < len - 4) {
                    ret[j + 1] = (byte) ((tmp & 0xff00) >> 8);
                    ret[j + 2] = (byte) (tmp & 0xff);
                    continue;
                }
                if (j + 1 < retLen)
                    ret[j + 1] = (byte) ((tmp & 0xff00) >> 8);
                if (j + 2 < retLen)
                    ret[j + 2] = (byte) (tmp & 0xff);
            }

            return ret;
        }

    }
}
